package top.swle.austers.controller;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import top.swle.austers.bean.ResponseBean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/upload_file")
public class FileController {

    @RequiresAuthentication
    @PostMapping("/img")
    public ResponseBean uploadImage(@RequestPart MultipartFile file) throws RuntimeException {
        if (file.isEmpty()) {
            return new ResponseBean(-1,"文件不能为空",null);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();

        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("上传的后缀名为：" + suffixName);
        // 文件上传后的路径
        String filePath = "D:\\lostandfound\\";
        // 解决中文问题，liunx下中文路径，图片显示问题
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
            System.out.println("不存在目录");
        }
        try {
            file.transferTo(dest);
            System.out.println("上传成功后的文件路径未：" + filePath + fileName);
            return new ResponseBean(1,fileName,null);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return new ResponseBean(-2,"上传失败",null);
    }
}
